package com.wushi.lenovo.asia5b.app_ui.h5;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.model.ResultModel;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_model.good.ThirdContentModel;
import com.wushi.lenovo.asia5b.app_model.good.bean.InterceptUrl;
import com.wushi.lenovo.asia5b.app_utils.helper.H5Hepler;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import butterknife.BindView;
import timber.log.Timber;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/3/18.
 */
public class ThirdContentActivity extends H5Activity {
    @BindView(R.id.webview_layout)
    LinearLayout webviewLayout;
    @BindView(R.id.progress)
    ContentLoadingProgressBar progress;
    @BindView(R.id.tv_title_titletext)
    TextView tv_title_titletext;
    protected String url;
    protected String title;
    protected WebView webView;

    public static void startThirdContentActivity(Context context, String url, String title) {
        url= H5Hepler.addAsiaH5Params(url);
        Intent intent = new Intent(context, ThirdContentActivity.class);
        intent.putExtra(H5_URL, url);
        intent.putExtra(H5_TITLE, title);
        context.startActivity(intent);
    }

    public static void startThirdContentActivityForFull(Context context, String url, String title) {
        Intent intent = new Intent(context, ThirdContentActivity.class);
        intent.putExtra(H5_URL, url);
        intent.putExtra(H5_TITLE, title);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_base_webview;
    }

    @Override
    protected WebView getWebView() {
        return webView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = getIntent().getStringExtra(H5_URL);
        String title = getIntent().getStringExtra(H5_TITLE);
        tv_title_titletext.setText(title);
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void initView() {
        //使用new方式这是为了解决当(settings.setJavaScriptEnabled(true))之后会出现TextToSpeech的内存泄漏
        webView = new WebView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        webView.setLayoutParams(layoutParams);
        webviewLayout.addView(webView);

        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);//支持缩放
        settings.setBuiltInZoomControls(true);//启用内置缩放装置
//        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//缓存
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//可能的话使所有列的宽度不超过屏幕宽度
        settings.setUseWideViewPort(true);//设置webview推荐使用的窗口
        settings.setLoadWithOverviewMode(true);//设置加载进来的页面自适应手机屏幕
        settings.setTextZoom(100); // 就可以禁止缩放，按照百分百显示。
        settings.setSavePassword(true);
        settings.setSaveFormData(true);
        settings.setGeolocationEnabled(true);
        settings.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
        //屏蔽的话，能阻止天猫弹出框，但是 也会导致显示不出天猫国际菜单栏和 拼多多里面商品的无法点击
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);
        //为什么要加这句，http://blog.csdn.net/u013320868/article/details/52837671 访问这个就可以了
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            //设置允许加载混合内容
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.requestFocus();
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        webView.setWebChromeClient(new ThirdWebChromeClient());
        webView.setWebViewClient(new ThirdWebViewClient());
    }

    @Override
    protected void initData() {
        webView.loadUrl(url);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    public void getProductIdByUrlResult(ResultModel<ThirdContentModel> resultModel) {
        if (resultModel.isSuccess()) {
            ThirdContentModel model = resultModel.getData();
            if (model != null && model.getId() > 0) {
                GoodsDetailsActivity.startGoodsDetailsActivity(mActivity, model.getId());
            }
        }
    }

    class ThirdWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progress.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                progress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                progress.setProgress(newProgress);//设置进度值
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    class ThirdWebViewClient extends WebViewClient {
//        @Override
//        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//            H5Hepler.alterSSL(mActivity,view,handler,error);
//        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                web_botice.loadUrl(url);//这样调用容易死循环  如果不需要对地址做特殊重定向处理 最好别重写此方法
            d("--->>>>>>>>---shouldOverrideUrlLoading");
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            d("--->>>>>>>>---onPageFinished");
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Timber.d("--->>>>>>>>---shouldOverrideUrlLoading");
            d("--->>>>>>>>---url:" + url);
            //https://item.taobao.com/item.htm?spm=a2141.8294655.guess.1&id=10664046906&scm=1007.15080.115528.0&pvid=2c5b770d-c704-45ca-9388-62c2f6613779&locate=guessitem-item&rmdChannelCode=guessULike&utparam=%7B%22guessModelVersion%22%3A%22%22%2C%22card_subtype%22%3A%22-%22%2C%22x_object_type%22%3A%22item%22%2C%22matrix_score%22%3A0.0%2C%22mtx_sab%22%3A3%2C%22miniapp_score%22%3A0.0%2C%22hybrid_score%22%3A0.0%2C%22card_type%22%3A%22-%22%2C%22tpp_buckets%22%3A%229420%230%23130763%230_9420%2391%23351%23533%22%2C%22miniapphc_score%22%3A0.0%2C%22mtx_ab%22%3A1%2C%22pvid%22%3A%222c5b770d-c704-45ca-9388-62c2f6613779%22%2C%22x_item_ids%22%3A10664046906%2C%22auction_score%22%3A0.0%2C%22x_sytab%22%3A%221001%22%2C%22x_object_id%22%3A10664046906%7D

            //地址不能为空
            if (TextUtils.isEmpty(url)) {
                url = "";
            }

            //不监测1688
            if (url.equals("https://m.1688.com/")) {
                d("--->>>>>>>>---不检测1688");
                return false;
            }


            //不监测淘宝和1688 主页面
            if (url.startsWith(InterceptUrl.TAOBAO_TEN)
                    || url.startsWith(InterceptUrl.TAOBAO_11)
                    || url.startsWith(InterceptUrl.ALIBABA_TWELVE)) {
                d("--->>>>>>>>---不监测淘宝和1688 主页面");
                return false;
            }

            //WebView拦截掉特殊的协议
            if (url.startsWith("tmall:") || url.startsWith("taobao:") || url.startsWith("openapp.jdmobile:")
                    || url.startsWith("mogujie:") || url.startsWith("jsbridge:")
                    || url.startsWith("http://mobile.yangkeduo.com/login.html") || url.startsWith("htao:") ||
                    url.startsWith("offer_search") || url.startsWith("alipays://platformapi/startapp") || url.startsWith("https://plogin.m.jd.com/user/login.action")) {
                d("--->>>>>>>>---WebView拦截掉特殊的协议");
                return true;
            }

            //WebView拦截掉1688的协议
            if (url.contains(InterceptUrl.ALIBABA_INTERCEPT1) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT2) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT3) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT4) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT5) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT6) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT7) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT8) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT9) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT10) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT11) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT12) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT13) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT14) ||
                    url.contains(InterceptUrl.ALIBABA_INTERCEPT15)) {
                d("--->>>>>>>>---WebView拦截掉1688的协议");
                return true;
            }

            //WebView拦截掉义乌购的协议
            if (url.contains(InterceptUrl.YWG_INTERCEPT1) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT2) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT3) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT4) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT5) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT6) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT7) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT8) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT9) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT10) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT11) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT12) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT13) ||
                    url.contains(InterceptUrl.YWG_INTERCEPT14)) {
                d("--->>>>>>>>---WebView拦截掉义乌购的协议");
                return true;
            }

            //WebView拦截掉蘑菇街的协议
            if (url.contains(InterceptUrl.MOGUJIE_INTERCEPT1) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT2) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT3) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT4) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT5) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT6) ||
                    url.contains(InterceptUrl.MOGUJIE_INTERCEPT7)) {
                d("--->>>>>>>>---WebView拦截掉蘑菇街的协议");
                return true;
            }

            //如果是淘宝第三方,继续加载网页
            if (isTaobaoThree(url)) {
                view.loadUrl(url);
                d("--->>>>>>>>---如果是淘宝第三方,继续加载网页");
                return true;
            }

            //跳转我们的详情
            if (url.indexOf("m.asia5b.com/goods.php?id") > -1) {
                interceptUrl(url);
                d("--->>>>>>>>---跳转我们的详情1");
                return true;
            }

            if (url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1) {//m.taobao.com/tbopen/index.html
                if (url.indexOf(InterceptUrl.TAOBAO_FOUR) > -1) {    //market
                    d("--->>>>>>>>---url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1");
                    return true;
                }
                Log.e("======dddddddddd", url);
                String remenUrl = "";
                try {
                    remenUrl = URLDecoder.decode(url, "utf-8");
                    Log.e("dd==-=-=-=-=-=-", remenUrl);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                int indexStart = remenUrl.indexOf("&h5Url=");
                String toStr = remenUrl.substring(indexStart + 7);
                if (toStr.indexOf("h5.m.taobao.com/awp/core/detail.htm") > -1) {
                    Log.e("qqqqqqq", toStr);
                    //跳转淘宝地址
                    interceptUrl2(toStr);
                    d("--->>>>>>>>---跳转淘宝地址2");
                    return true;
                }
            }


            //各大平台商品详情匹配规则
            if (url.indexOf(InterceptUrl.TMALL_ONE) > -1 || url.indexOf(InterceptUrl.TMALL_TWO) > -1
                    || url.indexOf(InterceptUrl.TAOBAO_ONE) > -1 || url.indexOf(InterceptUrl.TAOBAO_TWO) > -1
                    || url.indexOf(InterceptUrl.JD_ONE) > -1 || url.indexOf(InterceptUrl.JD_TWO) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_ONE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_TWO) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_THREE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_FOUR) > -1
                    || url.indexOf(InterceptUrl.MOGUJIE_FIVE) > -1 || url.indexOf(InterceptUrl.MOGUJIE_SIX) > -1
                    || url.indexOf(InterceptUrl.MEILISHUO_ONE) > -1 || url.indexOf(InterceptUrl.TAOBAO_THREE) > -1
                    || url.indexOf(InterceptUrl.JD_THREE) > -1 || url.indexOf(InterceptUrl.TAOBAO_EIGHT) > -1
                    || url.indexOf(InterceptUrl.PINDDD_ONE) > -1 || url.indexOf(InterceptUrl.TAOBAO_SIX) > -1
                    || url.indexOf(InterceptUrl.JD_FOUR) > -1 || url.indexOf(InterceptUrl.TAOBAO_FIVE) > -1//     m.taobao.com/tbopen/index.html
                    || url.indexOf(InterceptUrl.TAOBAO_SEVEN) > -1 || url.indexOf(InterceptUrl.ALIBABA_ONE) > -1
                    || url.indexOf(InterceptUrl.ALIBABA_TWO) > -1 || url.indexOf(InterceptUrl.ALIBABA_THREE) > -1
                    || url.indexOf(InterceptUrl.ALIBABA_FOUR) > -1 || url.indexOf(InterceptUrl.ALIBABA_FIVE) > -1
                    || url.indexOf(InterceptUrl.ALIBABA_SIX) > -1 || url.indexOf(InterceptUrl.ALIBABA_SEVEN) > -1
                    || url.indexOf(InterceptUrl.ALIBABA_EIGHT) > -1 || url.indexOf(InterceptUrl.ALIBABA_NIGHT) > -1
                    || url.indexOf(InterceptUrl.ALIBABA_TEN) > -1 || url.indexOf(InterceptUrl.ALIBABA_ELEVEN) > -1
                    || url.indexOf(InterceptUrl.YWG_ONE) > -1 || url.indexOf(InterceptUrl.YWG_TWO) > -1
                    || url.indexOf(InterceptUrl.YWG_THREE) > -1 || url.indexOf(InterceptUrl.YWG_FOUR) > -1
                    || url.indexOf(InterceptUrl.YWG_FIVE) > -1 || url.indexOf(InterceptUrl.YWG_SIX) > -1
                    || url.indexOf(InterceptUrl.YWG_SEVEN) > -1 || url.indexOf(InterceptUrl.YWG_EIGHT) > -1
                    || url.indexOf(InterceptUrl.YWG_NIGHT) > -1) {
                Log.e("kkkkk", url);
                //跳转淘宝地址
                interceptUrl(url);
                d("--->>>>>>>>---跳转淘宝地址3");
                return true;

            } else {
                view.loadUrl(url);//每次发起新的请求，在新的WebView中打开
                d("--->>>>>>>>---每次发起新的请求，在新的WebView中打开");
                return true;
            }
        }
    }

    public boolean isTaobaoThree(String url) {
        boolean isOne = false;
        if (url.indexOf(InterceptUrl.TAOBAO_EIGHT) > -1 && url.indexOf("item_id") > -1 && url.indexOf("expo_id") > -1) {
            isOne = true;
        }
        return isOne;
    }

    private void interceptUrl(String url) {
        getPresenter().getProductIdByUrl(url);
        d("第三方--->>>>>>>>---activityUrl1");

//        Intent intent = new Intent(this, CommodityDetActivity.class);
//        intent.putExtra("tmall", url);
//        startActivity(intent);
    }

    private void interceptUrl2(String url) {
        d("--->>>>>>>>---activityUrl2");
        getPresenter().getProductIdByUrl(url);
    }

}
